package com.example.demo.dao.daoimpl;

import com.example.demo.dao.AuthorityMapper;
import com.example.demo.pojo.RoleDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <h3>reqister</h3>
 * <p>查询权限</p>
 *
 * @author : chenjunjie
 * @date : 2021-06-22 09:50
 **/
@Repository
public class AuthorityMapperImpl implements AuthorityMapper {

    @Autowired
    DataSource dataSource;

    @Autowired
    JdbcTemplate template;

    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public List<String> getAuthoritys(Integer roleId) {
        List<String> list = template.queryForList("SELECT name FROM sys_authority join menu " +
                "where sys_authority.menu_id=menu.id and is_check=1 and role_id=?", String.class, roleId);
        return list;
    }

    @Override
    public List<RoleDetails> findParentAuthority(Integer roleId) {
        List<RoleDetails> roleDetails = template.query("SELECT sys_authority.menu_id,menu.name,sys_authority.is_check FROM sys_authority" +
                " join menu where sys_authority.role_id=? and sys_authority.menu_id=menu.id and menu.parent_id is null"
                , new RoleDetails(), roleId);
        return roleDetails;
    }

    @Override
    public List<RoleDetails> findChildrenAuthority(Integer parentId,Integer roleId) {
        List<RoleDetails> roleDetails = template.query("SELECT sys_authority.menu_id,menu.name,sys_authority.is_check FROM sys_authority " +
                "join menu where sys_authority.role_id=? and sys_authority.menu_id=menu.id and menu.parent_id =?"
                , new RoleDetails(), parentId, roleId);
        return roleDetails;
    }

    @Override
    public boolean updateAuthority(Integer roleId, List<Integer> menuId) {
        StringBuffer bufferSql=new StringBuffer("UPDATE sys_authority SET is_check = ( CASE ");
        for (Integer id : menuId) {
            String sql=" WHEN id = "+id+" THEN 0";
            bufferSql.append(sql);
        }
        bufferSql.append(" END ) WHERE id IN ( :ids)");
        Map<String,Object> map=new HashMap<>();
        map.put("ids",menuId);
        namedParameterJdbcTemplate.update(bufferSql.toString(),map);



        return false;
    }
}
